//
//  YDNetworkModule.swift
//  AR_Project
//
//  Created by alyadan on 16/6/28.
//  Copyright © 2016年 alyadan. All rights reserved.
//


import UIKit
import Alamofire
import SwiftyJSON
import RxSwift
import RxCocoa

public typealias YDNetworkSuccessResp = (data: [String: Any], origin: [String: JSON]?)
public typealias YDNetworkReq<T> = BehaviorRelay<Observable<T>?>

public protocol HTTPRespParserType {
    
    var responseDealBlock: ((Parameters?) -> Parameters?)? {get set}
    var paramsDealBlock: ((Parameters?) -> Parameters?)? {get set}

    func httpRequest(httpMethod:Alamofire.HTTPMethod, url:String, param:Parameters?, baseUrl: URL?, header: HTTPHeaders?) -> Observable<YDNetworkSuccessResp>
}


public enum YDNetworkError:Error {
    case paramError
    case connectError(url:String, param: Parameters?, error:Error)
    case serverError(url:String, param: Parameters? ,msg:String, code: Int)
    case responseDataError
    case loginExpire(url:String)
}


public class YDNetworkModule: NSObject {

    public var baseUrl:URL?

    public var httpRespParser: HTTPRespParserType = ExampleRspParser()
    
    public var defaultHeader: (() -> HTTPHeaders?)?
    
    public var paramDealBlock: ((Parameters?) -> Parameters?)?
    public var responseDealBlock: ((Parameters?) -> Parameters?)?
    
    public func request(method:HTTPMethod = .get, param:Parameters? = nil, url:String, header: HTTPHeaders? = nil) -> Observable<YDNetworkSuccessResp> {

        var header = header
        
        if header == nil {
            header = defaultHeader?()
        }
        
        httpRespParser.responseDealBlock = self.responseDealBlock

        return self.httpRespParser.httpRequest(httpMethod: method,  url: url, param: (paramDealBlock != nil) ? paramDealBlock?(param) : param, baseUrl: baseUrl, header: header)
        
    }
}

open class YDNetwork {
    
    public var network: YDNetworkModule
    
    public init(network: YDNetworkModule) {
        self.network = network
    }

    open func request(method:HTTPMethod = .get, param:Parameters? = nil, url:String, header: HTTPHeaders? = nil) -> Observable<YDNetworkSuccessResp> {
        return network.request(method: method, param: param, url: url, header: header)
    }
}

public var yd_network: YDNetwork = YDNetwork(network: YDNetworkModule())
